/**
 * Description:
 * Class Name:ExternalizablePerson
 * Date:2022/5/3 14:50
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第15章_输入输出._15_8_Java9改进的对象序列化._15_8_6_另一种自定义序列化机制;

import java.io.*;

public class ExternalizablePerson implements java.io.Externalizable{
    private String name;
    private int age;

    // 必须提供无参数的的构造器，否则反序列化时会失败
    public ExternalizablePerson(){
        System.out.println("无参数的构造器");
    }
    public ExternalizablePerson(String name, int age){
        System.out.println("有参数的构造器");
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(new StringBuilder(name).reverse());
        out.writeInt(age);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        this.name = ((StringBuilder)in.readObject()).reverse().toString();
        this.age = in.readInt();
    }

    public static void main(String[] args) {
        try (
                var oos = new ObjectOutputStream(new FileOutputStream("Chapter_15_8_6_external.txt"));
                var ois = new ObjectInputStream(new FileInputStream("Chapter_15_8_6_external.txt"));
                ){
            oos.writeObject(new ExternalizablePerson("aa", 10));
            ExternalizablePerson x1 = (ExternalizablePerson)ois.readObject();
            System.out.println(x1.getAge());
            System.out.println(x1.getName());
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
